﻿using UnityEngine;

namespace Utility
{
	public static class TransformEX
	{
		public static void Reset (this Transform transform)
		{
			transform.localPosition = Vector3.zero;
			transform.localRotation = Quaternion.identity;
			transform.localScale = Vector3.one;
		}

		/// <summary>
		/// set parent, and reset all locals to default
		/// </summary>
		/// <param name="transform"></param>
		/// <param name="parent"></param>
		public static void AnchorTo (this Transform transform, Transform parent, bool attachToParent = true)
		{
			transform.SetParent (parent);
			Reset (transform);
			if (!attachToParent)
			{
				transform.SetParent (null, true);
			}
		}

		public static Transform FindDeepChild (this Transform self, string path)
		{
			var result = self.Find (path);
			if (result != null)
			{
				return result;
			}

			foreach (Transform child in self)
			{
				result = child.FindDeepChild (path);
				if (result != null)
				{
					return result;
				}
			}
			return null;
		}

		public static T FindChildWithTypeAndName<T> (this Component self, string name)
			where T : Component
		{
			foreach (var componentOnChild in self.GetComponentsInChildren<T> ())
			{
				if (componentOnChild.transform.name.Contains (name))
				{
					return componentOnChild;
				}
			}

			return null;
		}
	}
}